/*
 * @Author: xujianxing
 * @Date: 2020-02-21 11:29:10
 * @LastEditors  : xujianxing
 * @LastEditTime : 2020-02-22 17:41:25
 * @Description: file content
 */
/** ---------拼接sql字符串函数----------START */

function insertData(table, datas) {
  var fields = "";
  var values = "";
  for (var k in datas) {
    const type = typeof datas[k] === "number";
    if (!!!datas[k]) continue;
    const funcType = typeof datas[k] === "string" && datas[k].includes("UUID"); // 包含UUID函数不加单引号
    fields += k + ",";
    values += type || funcType ? `${datas[k]},` : `'${datas[k]}',`;
  }
  fields = fields.slice(0, -1);
  values = values.slice(0, -1);
  var sql = "INSERT INTO " + table + "(" + fields + ") VALUES(" + values + ")";
  return sql;
}

/**
 * @param {sql table} table 表名
 * @param {Object} sets 设置的键值对
 * @param {Object} where 条件对象
 */
function updateSql(table, sets, where) {
  var _SETS = "";
  var _WHERE = "";
  for (var k in sets) {
    const val = typeof sets[k] === "number";
    _SETS += val ? `${k} = ${sets[k]}, ` : `${k} = '${sets[k]}', `;
  }
  _SETS = _SETS.replace(/,\s*$/g, "");
  for (var k2 in where) {
    const val = typeof where[k2] === "number";
    _WHERE += val ? `${k2} = ${where[k2]} AND ` : `${k2} = '${where[k2]}' AND `;
  }
  _WHERE = _WHERE.replace(/AND\s*$/g, ""); // 去掉末尾AND
  return "UPDATE " + table + " SET " + _SETS + " WHERE " + _WHERE;
}
/**
 *
 * @param {Object} 条件对象
 * 简单封装传入格式如下的条件参数，返回拼接好的sql查询
 * {username: 'admin'} 不加类型
 * { or: {username: 'xu', password: '123123'}}  或
 * { and: {username: 'xu', password: '123123'}} 且
 */
function findSql(table, data) {
  if (!data) {
    return `select * from ${table}`;
  }
  var sql = `select * from ${table} where `;
  var type = Object.entries(data)[0][0];
  var params = Object.entries(data)[0][1];
  if (typeof params !== "object") {
    if (typeof params !== "number") {
      params = `'${params}'`;
    }
    return `${sql} ${type} = ${params}`;
  }
  for (key in params) {
    if (typeof params[key] !== "number") {
      params[key] = `'${params[key]}'`;
    }
    sql += `${key} = ${params[key]} ${type} `;
  }
  return sql.replace(/(or|and)\s*$/g, "");
}
/**
 *
 * @param {String} table 表名
 * @param {Object} where 删除条件
 */
function removeSql(table, where) {
  var _WHERE = "";
  for (var key in where) {
    const type = typeof where[key] === "number";
    _WHERE += type ? `${key} = ${where[key]}, ` : `${key} = '${where[key]}', `;
  }
  _WHERE = _WHERE.replace(/,\s*$/g, "");
  var sql = "DELETE FROM " + table + " WHERE " + _WHERE;
  return sql;
}

/** ---------拼接sql字符串函数----------END */

module.exports = {
  insertData,
  findSql,
  updateSql,
  removeSql
};
